﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waiting : MonoBehaviour
{
    public GameObject body;

    private float z;
    private float rotationSpeed;

    private float timeCount = 0f;
    private float timeSize = 99999999f;

    public delegate void WaitTimeout();

    static private event WaitTimeout waitTimeout;

    private static Waiting gWaiting = null;

    public static void SetTimeout(WaitTimeout callback,bool enable)
    {
        if(enable)
        {
            waitTimeout += callback;
        }
        else
        {
            waitTimeout -= callback;
        }
    }

    public static bool SetActive(bool active,float timeSize = 5.0f)
    {
        if(null == gWaiting)
        {
            if(!active)
            {
                return false;
            }

            var root = GameUtils.Instance().UiRoot;
            if(null == root)
            {
                Debug.LogError("not find ui root");
                return false;
            }

            Object prefabObj = Resources.Load("prefabs/waiting");
            if(null == prefabObj)
            {
                Debug.LogError("Resources load prefabs/waiting failed.");
                return false;
            }

            GameObject go = (GameObject)Instantiate(prefabObj);
            go.transform.SetParent(root.transform);
            var rectTran = (RectTransform)go.transform;
            rectTran.offsetMin = new Vector2(0,0);
            rectTran.offsetMax = new Vector2(0,0);

            var self = go.GetComponent<Waiting>();
            self.timeSize = timeSize;
            self.timeCount = 0f;
        }
        else
        {
            gWaiting.gameObject.SetActive(active);
            if(active)
            {
                gWaiting.timeSize = timeSize;
                gWaiting.timeCount = 0f;
            }
        }

        return true;
    }

    void Awake()
    {
        gWaiting = this;
    }

    void Start()
    {
        z = 0.0f;
        rotationSpeed = 75.0f;
    }

    void FixedUpdate()
    {
        z += Time.deltaTime * rotationSpeed;

        if (z > 360.0f)
        {
            z = 0.0f;
        }

        body.transform.localRotation = Quaternion.Euler(0, 0, z);

        timeCount += Time.deltaTime;
        if(timeCount >= timeSize)
        {
            timeCount = 0f;
            gameObject.SetActive(false);

            if(waitTimeout != null)
            {
                waitTimeout();
            }
        }
    }

    void OnDestroy()
    {
        if(this == gWaiting)
        {
            gWaiting = null;
        }
    }
}
